/**
 * @description 格式化时间, 根据规则显示不同格式的时间字符串
 * @param {*} timestamp 时间戳
 * @returns {string} 格式化后的时间
 */
export function conversationListTimeFormatter(timestamp) {
  if (!timestamp) return "";

  const date = new Date(timestamp);
  const now = new Date();

  // 计算时间差（单位：毫秒）
  // const timeDiff = now.getTime() - date.getTime()

  // 检查是否是当天的时间
  if (
    date.getDate() === now.getDate() &&
    date.getMonth() === now.getMonth() &&
    date.getFullYear() === now.getFullYear()
  ) {
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    return `${hours}:${minutes}`;
  }

  // 检查是否是昨天的时间
  const yesterday = new Date(now);
  yesterday.setDate(now.getDate() - 1);
  if (
    date.getDate() === yesterday.getDate() &&
    date.getMonth() === yesterday.getMonth() &&
    date.getFullYear() === yesterday.getFullYear()
  )
    return "昨天";

  // 检查是否是一周内的时间
  // const oneWeekAgo = new Date(now)
  // oneWeekAgo.setDate(now.getDate() - 7)
  // if (date >= oneWeekAgo) {
  // 	const daysOfWeek = ['日', '一', '二', '三', '四', '五', '六']
  // 	const dayOfWeek = daysOfWeek[date.getDay()]
  // 	return `星期${dayOfWeek}`
  // }

  // 一年以内
  const year = String(date.getFullYear());
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");

  const timeGap = Math.abs(now.getTime() - date.getTime()); // 时间差（单位：毫秒）
  if (timeGap / (1000 * 60 * 60 * 24) < 365) return `${month}.${day}`;

  // 一年以上
  return `${year}.${month}.${day}`;
}
/**
 * 将时间戳转换为符合规则的时间字符串。
 * 今天： HH:mm
 * 昨天： 昨天 HH:mm
 * 7天内:  星期W HH:mm
 * 更早: YYYY-MM-DD HH:mm
 * @param {number} timestamp - 时间戳, 单位为毫秒。
 * @returns {string} 格式化后的时间字符串。
 */
export function messageListTimeFormatter(timestamp) {
  function padZero(value) {
    return value.toString().padStart(2, "0");
  }
  function formatDate(date, format) {
    const year = date.getFullYear();
    const month = padZero(date.getMonth() + 1);
    const day = padZero(date.getDate());
    const hours = padZero(date.getHours());
    const minutes = padZero(date.getMinutes());

    return format
      .replace("YYYY", year)
      .replace("MM", month)
      .replace("DD", day)
      .replace("HH", hours)
      .replace("mm", minutes);
  }

  const currentDate = new Date();
  const targetDate = new Date(timestamp);

  const currentYear = currentDate.getFullYear();
  const currentMonth = currentDate.getMonth();
  const currentDay = currentDate.getDate();

  const targetYear = targetDate.getFullYear();
  const targetMonth = targetDate.getMonth();
  const targetDay = targetDate.getDate();

  if (
    currentYear === targetYear &&
    currentMonth === targetMonth &&
    currentDay === targetDay
  ) {
    // 今天
    return formatDate(targetDate, "HH:mm");
  } else if (
    currentYear === targetYear &&
    currentMonth === targetMonth &&
    currentDay - targetDay === 1
  ) {
    // 昨天
    return `昨天 ${formatDate(targetDate, "HH:mm")}`;
  } else if (
    currentYear === targetYear &&
    currentMonth === targetMonth &&
    currentDay - targetDay <= 7
  ) {
    // 7天内
    const weekday = ["日", "一", "二", "三", "四", "五", "六"][
      targetDate.getDay()
    ];
    return `星期${weekday} ${formatDate(targetDate, "HH:mm")}`;
  } else {
    // 更早
    return formatDate(targetDate, "YYYY-MM-DD HH:mm");
  }
}

/**
 * 判断当前时间是否在给定时间段内
 * @param {string} startTime - 开始时间, 格式为 "HH:mm", 例如 "18:00"
 * @param {string} endTime - 结束时间, 格式为 "HH:mm", 例如 "20:00"
 * @param {boolean} [nextDay] - 是否跨天, 默认为 false
 * @returns {boolean} - 当前时间是否在给定时间段内
 */
export function isTimeInRange(startTime, endTime, nextDay = false) {
  const now = new Date(); // 获取当前时间
  const currentHour = now.getHours();
  const currentMinute = now.getMinutes();

  const [startHour, startMinute] = startTime.split(":").map(Number);
  const [endHour, endMinute] = endTime.split(":").map(Number);

  // 构造开始时间和结束时间的 Date 对象
  const startDate = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate(),
    startHour,
    startMinute
  );
  const endDate = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate(),
    endHour,
    endMinute
  );

  // 如果 nextDay 为 true, 则结束时间在开始时间之前, 表示跨天
  if (nextDay && endDate < startDate) endDate.setDate(endDate.getDate() + 1); // 结束时间加一天

  // 构造当前时间的 Date 对象
  const currentTime = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate(),
    currentHour,
    currentMinute
  );

  // 判断当前时间是否在给定时间段内
  if (currentTime >= startDate && currentTime <= endDate) return true;
  else return false;
}

/**
 *
 * @param {string} time
 * @returns {string} 格式化后的时间
 */
export function fixIOSTime(time) {
  if (time) return time.replace(/-/g, "/");
  return time;
}

/**
 * @description 传入不带时区的时间字符串，返回修正后的时间戳
 * @param {string} time 接口返回的时间字符串
 * @param {number} [timezone] 时区，默认为 8
 * @returns {number} 修正后的时间戳
 */
export function fixApiTimeToUTC8(time, timezone = 8) {
  if (!time) return time;
  const targetDate = new Date(time.replace(/-/g, "/"));
  const targetTimeStamp = targetDate.getTime();

  const currentTimeZone = new Date().getTimezoneOffset();
  const utc = targetTimeStamp - currentTimeZone * 60000; // 得到UTC时间
  const fixedTime = utc - 3600000 * timezone; // 时区修正
  return fixedTime;
}

let timeDiff = null;
let timeDiffPromise = null;
export async function getTimeStamp() {
  if (timeDiff !== null) return Date.now() + timeDiff;

  async function setTimeDiff() {
    const { VITE_API_URL } = import.meta.env;
    const data = await fetch(`${VITE_API_URL}/server/time`).then(res =>
      res.json()
    ); // 不能调用封装的请求方法
    timeDiff = data.data - Date.now();
  }

  if (!timeDiffPromise) timeDiffPromise = setTimeDiff();

  await timeDiffPromise;
  return Date.now() + timeDiff; // 返回正确时间戳
}

/**
 * @description 获取本地时间的年月日
 * @returns {string} 当前时间 示例：2024-09-06
 */
export function getLocalToday() {
  const today = new Date();
  const todayString = today.toISOString().split("T")[0];
  return todayString;
}
